package com.gnerv.sylvanas.module.sse.listener;

import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.CountDownLatch;

@EqualsAndHashCode(callSuper = true)
@Slf4j
@Data
public class SSEListener extends EventSourceListener {

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    private HttpServletResponse rp;
    private String clientId;

    private StringBuffer output = new StringBuffer();

    public SSEListener(HttpServletResponse response) {
        this.rp = response;
    }

    /**
     * {@inheritDoc}
     * 建立sse连接
     */
    @Override
    public void onOpen(final EventSource eventSource, final Response response) {
        if (rp != null) {
            rp.setContentType("text/event-stream");
            rp.setCharacterEncoding("UTF-8");
            rp.setStatus(200);
            log.info("建立sse连接...");
        } else {
            log.info("客户端非sse推送");
        }
    }

    /**
     * 事件
     *
     * @param eventSource
     * @param id
     * @param type
     * @param data
     */
    @Override
    public void onEvent(EventSource eventSource, String id, String type, String data) {
        try {
            output.append(data);
            PrintWriter printWriter = rp.getWriter();

            printWriter.write("event:" + type + "\n");
            printWriter.write("id:" + clientId + "\n");
            String dataReplace = data.replaceAll("\n", "[ENTRY]");
            printWriter.write("data:" + dataReplace + "\n\n");
            printWriter.flush();

            if ("finish".equals(type)) {
                log.info("请求结束:{}", clientId);
            }
            if ("error".equals(type)) {
                printWriter.close();
                log.info("{}: {}source {}", clientId, data, clientId);
            }


        } catch (Exception e) {
            log.error("消息错误[" + clientId + "]", e);
            countDownLatch.countDown();
            throw new RuntimeException(e);
        }

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onClosed(final EventSource eventSource) {
        log.info("sse连接关闭:{}", clientId);
        log.info("结果输出:{}" + output.toString());
        try {
            rp.getWriter().close();
            log.info("与客户端连接关闭:{}", clientId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        countDownLatch.countDown();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onFailure(final EventSource eventSource, final Throwable t, final Response response) {
        log.error("使用事件源时出现异常... [响应：{}]...", clientId);
        countDownLatch.countDown();
    }

}
